package com.videoweb.domain.conversation.entity;

import com.videoweb.domain.conversation.valueobject.ConversationContext;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Conversation聚合根
 * 对话实体，管理对话的完整生命周期和消息
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Conversation {
    
    private Long id;
    private String title;
    private Long agentId;
    private Long userId;
    private Integer status; // 1:进行中, 2:已结束
    private Integer messageCount;
    private Integer totalTokens;
    private LocalDateTime lastMessageAt;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
    
    // 聚合内的消息集合
    @Builder.Default
    private List<Message> messages = new ArrayList<>();
    
    // 对话上下文
    private ConversationContext context;
    
    /**
     * 添加消息到对话中
     */
    public void addMessage(Message message) {
        if (message == null) {
            throw new IllegalArgumentException("Message cannot be null");
        }
        
        if (!isActive()) {
            throw new IllegalStateException("Cannot add message to inactive conversation");
        }
        
        // 设置消息的对话ID
        message.setConversationId(this.id);
        
        // 添加到消息列表
        this.messages.add(message);
        
        // 更新统计信息
        this.messageCount = this.messages.size();
        this.totalTokens = this.totalTokens != null ? this.totalTokens + message.getTokenCount() : message.getTokenCount();
        this.lastMessageAt = message.getCreatedAt();
        this.updatedAt = LocalDateTime.now();
        
        // 自动生成标题（基于第一条用户消息）
        if (this.title == null || this.title.equals("新对话")) {
            generateTitleFromFirstUserMessage();
        }
    }
    
    /**
     * 检查对话是否活跃
     */
    public boolean isActive() {
        return this.status != null && this.status == 1;
    }
    
    /**
     * 结束对话
     */
    public void finish() {
        this.status = 2;
        this.updatedAt = LocalDateTime.now();
    }
    
    /**
     * 重新激活对话
     */
    public void reactivate() {
        this.status = 1;
        this.updatedAt = LocalDateTime.now();
    }
    
    /**
     * 获取最后几条消息（用于上下文）
     */
    public List<Message> getLastMessages(int count) {
        if (messages.isEmpty()) {
            return new ArrayList<>();
        }
        
        int fromIndex = Math.max(0, messages.size() - count);
        return new ArrayList<>(messages.subList(fromIndex, messages.size()));
    }
    
    /**
     * 获取用户消息数量
     */
    public int getUserMessageCount() {
        return (int) messages.stream()
                .filter(msg -> "user".equals(msg.getRole()))
                .count();
    }
    
    /**
     * 获取助手消息数量
     */
    public int getAssistantMessageCount() {
        return (int) messages.stream()
                .filter(msg -> "assistant".equals(msg.getRole()))
                .count();
    }
    
    /**
     * 检查是否需要总结上下文
     */
    public boolean needsContextSummary() {
        return this.messageCount != null && this.messageCount > 20; // 超过20条消息需要总结
    }
    
    /**
     * 更新对话上下文
     */
    public void updateContext(ConversationContext newContext) {
        this.context = newContext;
        this.updatedAt = LocalDateTime.now();
    }
    
    /**
     * 根据第一条用户消息生成标题
     */
    private void generateTitleFromFirstUserMessage() {
        Message firstUserMessage = messages.stream()
                .filter(msg -> "user".equals(msg.getRole()))
                .findFirst()
                .orElse(null);
        
        if (firstUserMessage != null && firstUserMessage.getContent() != null) {
            String content = firstUserMessage.getContent().trim();
            // 取前30个字符作为标题
            this.title = content.length() > 30 ? content.substring(0, 30) + "..." : content;
        }
    }
    
    /**
     * 验证对话数据完整性
     */
    public boolean isValid() {
        return agentId != null 
            && userId != null 
            && status != null 
            && (status == 1 || status == 2);
    }
    
    /**
     * 创建新对话
     */
    public static Conversation createNew(Long agentId, Long userId, String initialTitle) {
        LocalDateTime now = LocalDateTime.now();
        return Conversation.builder()
                .title(initialTitle != null ? initialTitle : "新对话")
                .agentId(agentId)
                .userId(userId)
                .status(1) // 新对话默认激活
                .messageCount(0)
                .totalTokens(0)
                .createdAt(now)
                .updatedAt(now)
                .messages(new ArrayList<>())
                .build();
    }
}